import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @description: 449. 序列化和反序列化二叉搜索树
* @author hewei
* @date 2022/8/4 14:24
* @version 1.0
*/

public class Codec2 {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "#";
        return root.val + "," + serialize(root.left) + "," + serialize(root.right);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] split = data.split(",");
        return process(new ArrayList<>(Arrays.asList(split)));
    }

    public TreeNode process(List<String> list) {
        if (list.get(0).equals("#")) {
            list.remove(0);
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(list.get(0)));
        list.remove(0);
        node.left = process(list);
        node.right = process(list);
        return node;
    }
}
